package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mng/cache"
	"novel-mng/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	off := (page - 1) * size
	var novel []models.Novel
	redis_list_key := "list_page_" + strconv.Itoa(int(page))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheData == "" {
		models.DB.Offset(off).Limit(size).Find(&novel)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	var total int64
	models.DB.Model(&models.Novel{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"total": total,
		"data":  novel,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var novel models.Novel
	redis_list_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheData == "" {
		models.DB.First(&novel, id)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情成功",
		"data": novel,
	})
	return
}
